<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\common\utils\JsonResponse;
use think\App;
use app\admin\validate\MenuValidate;
use think\facade\Request;
use app\common\model\Menu as MenuModel;

class Menu extends AdminController
{
    protected MenuModel $menuModel;
    
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->menuModel = new MenuModel();
    }
    
    /**
     * 获取菜单列表
     * @permission system:menu:getList
     */
    public function getList()
    {
        try {
            // 获取所有菜单
            $menus = $this->menuModel->field('menu_id,parent_id,name,path,component,redirect,title,icon,is_custom_svg,type,perms,sort,status,no_keep_alive,hidden,create_time')
                ->order('sort', 'asc')
                ->order('menu_id', 'asc')
                ->select()
                ->toArray();
                
            // 转换为树状结构
            $tree = $this->buildTree($menus);
                
            return JsonResponse::success($tree);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
    
    /**
     * 构建树状结构
     * @param array $items
     * @param int $parentId
     * @return array
     */
    protected function buildTree(array $items, int $parentId = 0): array
    {
        $tree = [];
        foreach ($items as $item) {
            if ($item['parent_id'] == $parentId) {
                $children = $this->buildTree($items, $item['menu_id']);
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }
    
    /**
     * 添加菜单
     * @permission system:menu:doAdd
     */
    public function doAdd()
    {
        $params = Request::post();
        
        try {
            validate(MenuValidate::class)
                ->scene('add')
                ->check($params);
                
            // 检查菜单标识是否存在
            if (!empty($params['perms']) && $this->menuModel->where('perms', $params['perms'])->find()) {
                return JsonResponse::error('权限标识已存在');
            }
            
            $data = [
                'parent_id' => $params['parent_id'] ?? 0,
                'name' => $params['name'] ?? '',
                'path' => $params['path'] ?? '',
                'component' => $params['component'] ?? '',
                'redirect' => $params['redirect'] ?? '',
                'title' => $params['title'] ?? '',
                'icon' => $params['icon'] ?? '',
                'is_custom_svg' => $params['is_custom_svg'] ?? 0,
                'type' => $params['type'] ?? 1,
                'perms' => $params['perms'] ?? '',
                'sort' => $params['sort'] ?? 0,
                'status' => $params['status'] ?? 1,
                'no_keep_alive' => $params['no_keep_alive'] ?? 0,
                'hidden' => $params['hidden'] ?? 0
            ];
            
            if ($this->menuModel->save($data)) {
                return JsonResponse::success([], '添加成功');
            }
            return JsonResponse::error('添加失败');
            
        } catch (\think\exception\ValidateException $e) {
            return JsonResponse::error($e->getMessage());
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
    
    /**
     * 修改菜单
     * @permission system:menu:doEdit
     */
    public function doEdit()
    {
        $params = Request::post();
        
        try {
            validate(MenuValidate::class)
                ->scene('edit')
                ->check($params);
                
            $menu = $this->menuModel->find($params['menu_id']);
            if (!$menu) {
                return JsonResponse::error('菜单不存在');
            }
            
            // 检查权限标识是否被其他菜单使用
            if (!empty($params['perms']) && $this->menuModel->where('perms', $params['perms'])
                ->where('menu_id', '<>', $params['menu_id'])
                ->find()) {
                return JsonResponse::error('权限标识已存在');
            }
            
            $data = [
                'parent_id' => $params['parent_id'] ?? 0,
                'name' => $params['name'] ?? '',
                'path' => $params['path'] ?? '',
                'component' => $params['component'] ?? '',
                'redirect' => $params['redirect'] ?? '',
                'title' => $params['title'] ?? '',
                'icon' => $params['icon'] ?? '',
                'is_custom_svg' => $params['is_custom_svg'] ?? 0,
                'type' => $params['type'] ?? 1,
                'perms' => $params['perms'] ?? '',
                'sort' => $params['sort'] ?? 0,
                'status' => $params['status'] ?? 1,
                'no_keep_alive' => $params['no_keep_alive'] ?? 0,
                'hidden' => $params['hidden'] ?? 0
            ];
            
            if ($menu->save($data)) {
                return JsonResponse::success([], '修改成功');
            }
            return JsonResponse::error('修改失败');
            
        } catch (\think\exception\ValidateException $e) {
            return JsonResponse::error($e->getMessage());
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
    
    /**
     * 删除菜单
     * @permission system:menu:doDelete
     */
    public function doDelete()
    {
        $params = Request::post();
        
        try {
            $menu = $this->menuModel->find($params['menu_id']);
            if (!$menu) {
                return JsonResponse::error('菜单不存在');
            }
            
            // 检查是否有子菜单
            if ($this->menuModel->where('parent_id', $params['menu_id'])->count() > 0) {
                return JsonResponse::error('请先删除子菜单');
            }
            
            // 检查是否被角色使用
            if ($this->menuModel->isMenuUsed($params['menu_id'])) {
                return JsonResponse::error('该菜单已被角色使用，无法删除');
            }
            
            if ($menu->delete()) {
                return JsonResponse::success([], '删除成功');
            }
            return JsonResponse::error('删除失败');
            
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
    
    /**
     * 获取路由列表
     */
    public function getRouters()
    {
        try {
            // 直接传入角色列表获取路由
            $menus = $this->menuModel->getRouters($this->adminInfo['roles'] ?? []);
            return JsonResponse::success([
                'list' => $menus,
                'home_path' => '/dashboard'  // 默认首页路径
            ]);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
} 